<?php
use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
use \GatewayWorker\Lib\DbConnection;
use \Workerman\Lib\Timer;


class Events
{
    public static $users;
    public static $chats;
    public static $games;
    public static $utility;
    public static $DBFIXET = 'rp_';

	//进程启动后初始化数据库连接
    public static function onWorkerStart($worker)
    {
        require_once __DIR__."/Libs/RpcClient.php";
        require_once __DIR__."/Libs/Utility.php";
        require_once __DIR__."/Libs/Users.lib.php";
        require_once __DIR__."/Libs/Chat.lib.php";
        require_once __DIR__."/Libs/Game.lib.php";

        global $db;
        global $redis;
        global $utility;
        $db = Db::instance('db');
		//连接Redis
        $redis = new Redis();
        $redis->connect(\Config\Redis::$redis['host'], \Config\Redis::$redis['port']);
        if(isset(\Config\Redis::$redis['auth']) && !empty(\Config\Redis::$redis['auth'])) {
            $redis->auth(\Config\Redis::$redis['auth']);
        }
		//检测是否连接成功
		// echo "Redis Server is running: ".$redis->ping()."\n";
        $utility = new \App\Libs\Utility($db, $redis, $utility);
        self::$utility = $utility;
        self::$users = new \App\Libs\Users($db, $redis, $utility);
        self::$games = new \App\Libs\Games($db, $redis, $utility);
        self::$chats = new \App\Libs\Chats($db, $redis, $utility);

    }
	public static function onConnect($client_id)
    {

        //self::$redis->incr(self::$DBFIXET.'user_nums');
        //self::$redis->sadd(self::$DBFIXET.'client_list', $client_id);
    }
    public  static function onMessage($client_id, $message)
    {
        global $db;
        global $redis;
        global $utility;

        /*
            //打印测试数据
            echo "------------------------------------------------------------------\n";
            echo "Client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']}" . "\n";
            echo "Client_ID:{$client_id}, dateTime:" . date('Y-m-d H:i:s', time()) . "\n";
            echo "SESSION:" . json_encode($_SESSION) . "\n";
            echo "onMessage:" . $message . "\n";
            //打印测试数据结束
        */

        // 客户端传递的须是json数据，并做检验
        $paras = json_decode($message, true);
        if(!$paras)
        {
            //echo 'onMessage Paras error!'."\n";
            Gateway::sendToCurrentClient(json_encode(array(
                'state' => 404,
                'msgid' => 404,//数据格式不正确
            )));
            Gateway::closeClient($client_id);
            return;
        }
        //组织共用的数据传给其它类
        /*
        $workParas = array(
            'db' => $db,
            'prefix' => self::$DBFIXET,
            'redis' => $redis,
        );
        */
        $whereFrom = self::$utility->existsKeyInArray('from',$paras,'S','pong');
        //没果没有指令即返回错误
        $Cmd = self::$utility->existsKeyInArray('cmd',$paras,'S');
        if(empty($Cmd))
        {
            //echo 'onMessage Paras error!'."\n";
            Gateway::sendToCurrentClient(json_encode(array(
                'state' => 404,
                'msgid' => 404,//数据格式不正确
            )));
            Gateway::closeClient($client_id);
            return;
        }

        # 记录IP地址
        $paras['remoteip'] = $_SESSION['remoteip'];
        switch($whereFrom)
        {
            case 'chat': //聊天事件
                self::$chats->chatMessage($client_id, $paras);
                break;
            case 'game': //游戏事件
                self::$games->gameMessage($client_id, $paras);
                break;
            case 'public': //公共事件
                self::$users->userMessage($client_id, $paras);
                break;
            default:
                //如果room_id和red_issue不为空即加入这个组
                $room_id = self::$utility->existsKeyInArray('room_id',$paras,'S');
                $red_issue = self::$utility->existsKeyInArray('red_issue',$paras,'S');
                if(!empty($red_issue)){
                    Gateway::joinGroup($client_id,$red_issue);
                }else{
                    if(!empty($room_id)){
                        Gateway::joinGroup($client_id, $room_id);
                    }
                }
                $all_user = array(
                    'cmd' => 'pong',
                    //'online' => Gateway::getClientCountByGroup('public'),
                );
                Gateway::sendToCurrentClient(json_encode($all_user));
                return;
                break;
        }
    }
   
   /**
    * 当客户端断开连接时
    * @param integer $client_id 客户端id
    */
   public static function onClose($client_id)
   {
	   //self::$redis->decr(self::$DBFIXET.'user_nums');
       //self::$redis->srem(self::$DBFIXET.'client_list', $client_id);
       //修正redis中的self::$DBFIXET.'client_list'
       # self::$redis->set(self::$DBFIXET.'user_nums',self::$redis->zcard(self::$DBFIXET.'client_list'));
       // debug
       //echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} client_id:$client_id onClose:''\n";
       
       // 从房间的客户端列表中删除
       //if(isset($_SESSION['token']))
       //{
           //退出聊天室
            if(isset($_SESSION['uno']) && isset($_SESSION['nickname'])){
                $result = array('cmd'=>'logout', 'from_uno'=>$_SESSION['uno'], 'from_nickname'=>$_SESSION['nickname'], 'time'=>date('Y-m-d H:i:s'));
                if(isset($_SESSION['room_id'])) {
                    $room_id = $_SESSION['room_id'];
                    //聊天室要返回昵称
                    Gateway::sendToGroup($room_id, json_encode($result));
                }
           // }
       }
   }
  
}
